import '../enum/MessageType.dart';

class ChatList {
  final int messageId;
  final int userId;
  late String avatar;
  late String name;
  late MessageType messageType;
  late String lastContent;

  ChatList({
    required this.messageId,
    required this.userId,
    required this.avatar,
    required this.name,
    required this.messageType,
    required this.lastContent,
  });

  /// 从 JSON 解析
  factory ChatList.fromJson(Map<String, dynamic> json) {
    return ChatList(
      messageId: json['messageId'] is int
          ? json['messageId']
          : int.tryParse(json['messageId']?.toString() ?? '') ?? 0,
      userId: json['userId'] is int
          ? json['userId']
          : int.tryParse(json['userId']?.toString() ?? '') ?? 0,
      avatar: json['avatar']?.toString() ?? '',
      name: json['name']?.toString() ?? '',
      messageType: _parseMessageType(json['messageType']),
      lastContent: json['lastContent']?.toString() ?? '',
    );
  }

  /// 转换为 JSON
  Map<String, dynamic> toJson() {
    return {
      'messageId': messageId,
      'userId': userId,
      'avatar': avatar,
      'name': name,
      'messageType': messageType.name,
      'lastContent': lastContent,
    };
  }

  /// 类型解析
  static MessageType _parseMessageType(dynamic value) {
    if (value == null) return MessageType.text;
    final str = value.toString().toLowerCase();
    switch (str) {
      case "text":
        return MessageType.text;
      case "image":
        return MessageType.image;
      case "video":
        return MessageType.video;
      case "emoji":
        return MessageType.emoji;
      default:
        return MessageType.text;
    }
  }
}
